package com.ccteam.fluidmusic.ui.album

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.ccteam.fluidmusic.NavDescriptionDirections
import com.ccteam.fluidmusic.NavMoreMusicDirections
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentAlbumDetailBinding
import com.ccteam.fluidmusic.utils.TransitionUtils
import com.ccteam.fluidmusic.utils.generateContainerTransform
import com.ccteam.fluidmusic.ui.moment.AddMomentActivity
import com.ccteam.fluidmusic.view.adapters.GlobalAlbumDetailItemAdapter
import com.ccteam.fluidmusic.view.base.LightBounceEdgeEffectFactory
import com.ccteam.fluidmusic.view.bean.*
import com.ccteam.fluidmusic.view.fragments.common.DescriptionData
import com.ccteam.fluidmusic.widget.AnimToolbarScrollListener
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import com.ccteam.model.moment.MOMENT_SHARE_TYPE_ALBUM
import com.ccteam.shared.result.album.AlbumDetailHeaderItem
import com.ccteam.shared.result.album.AlbumDetailMusicItem
import com.ccteam.shared.result.moment.MomentListItem
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

@AndroidEntryPoint
class AlbumDetailFragment : Fragment() {

    private var _binding: FragmentAlbumDetailBinding? = null
    private val binding get() = _binding!!

    @Inject
    lateinit var lightBounceEdgeEffectFactory: LightBounceEdgeEffectFactory

    private val albumDetailViewModel: AlbumDetailViewModel by viewModels()
    private val mainActivityViewModel: MainActivityViewModel by activityViewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        exitTransition = TransitionUtils.exitScale
        reenterTransition = TransitionUtils.enterScale
        // 设置共享动画
        sharedElementEnterTransition = generateContainerTransform(requireContext())
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentAlbumDetailBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        val adapter =  GlobalAlbumDetailItemAdapter(callback)
        binding.rvAlbumDetail.adapter = adapter
        lightBounceEdgeEffectFactory.applyBounceView(binding.rvAlbumDetail,this)
        binding.rvAlbumDetail.edgeEffectFactory = lightBounceEdgeEffectFactory

        binding.toolbarAlbumDetail.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        binding.rvAlbumDetail.addOnScrollListener(
            AnimToolbarScrollListener(binding.toolbarTitle,0.75f)
        )

        albumDetailViewModel.shouldShowShareButton.observe(viewLifecycleOwner, {
            binding.toolbarAlbumDetail.menu.findItem(R.id.toolbar_share).isVisible = it
        })

        albumDetailViewModel.albumHeader.observe(viewLifecycleOwner, {
            adapter.header = it
            if(!it.isNullOrEmpty()){
                binding.toolbarTitle.text = it[0].albumTitle
            }
        })
        albumDetailViewModel.albumMusicList.observe(viewLifecycleOwner, {
            adapter.albumMusicList = it
        })

        albumDetailViewModel.loadMessage.observe(viewLifecycleOwner, {
            binding.statusView.changeToErrorStatus(it)
            binding.statusView.changeToLoadingStatus(it is LoadMessage.Loading)
        })

        binding.statusView.setRetryClickListener {
            albumDetailViewModel.refreshAlbumDetail()
        }

        binding.toolbarAlbumDetail.setOnMenuItemClickListener { menuItem ->
            return@setOnMenuItemClickListener when(menuItem.itemId){
                R.id.toolbar_share ->{
                    val albumInfo = albumDetailViewModel.albumHeader.value!![0]
                    startActivity(Intent(requireContext(), AddMomentActivity::class.java).apply {
                        putExtra("shareContent", MomentListItem.MomentShareItem(
                            albumInfo.albumId, MOMENT_SHARE_TYPE_ALBUM,albumInfo.albumTitle,albumInfo.artist,albumInfo.albumArtUri
                        ))
                    })
                    true
                }
                else ->
                    false
            }
        }
    }

    private val callback = object: GlobalAlbumDetailItemAdapter.ItemClickedCallback{
        override fun playButtonClicked(view: View) {
            albumDetailViewModel.albumMusicList.value?.let {
                if(!it.isNullOrEmpty()){
                    mainActivityViewModel.playMediaId(it[0].mediaId,albumDetailViewModel.parentId.value,false)
                }
            }
        }

        override fun shufflePlayButtonClicked(view: View) {
            albumDetailViewModel.albumMusicList.value?.let {
                if(!it.isNullOrEmpty()){
                    mainActivityViewModel.playMediaId(it[(it.indices).random()].mediaId,albumDetailViewModel.parentId.value,false)
                }
            }
        }

        override fun moreAlbumDescriptionClicked(view: View, description: AlbumDetailHeaderItem) {
            findNavController().navigate(
                NavDescriptionDirections.actionGlobalDescriptionDialog(
                DescriptionData(description.albumTitle,description.description!!)
            ))
        }

        override fun musicItemClicked(view: View, musicItem: AlbumDetailMusicItem) {
            mainActivityViewModel.playMediaId(musicItem.mediaId, albumDetailViewModel.parentId.value,false)
        }

        override fun musicItemMoreClicked(view: View, musicItem: AlbumDetailMusicItem) {
            findNavController().navigate(NavMoreMusicDirections.actionGlobalMusicMoreBottomSheetFragment(
                MoreInfoData(albumDetailViewModel.parentId.value!!,musicItem.mediaId,
                    musicItem.title,musicItem.artist,false,null,
                    musicItem.artistInfo,albumDetailViewModel.albumHeader
                        .value?.get(0)?.albumArtUri,
                    canShare = albumDetailViewModel.isLogin.value == true)
            ))
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}